<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="深入理解mybatis（五）java apiSqlSessionFactoryBuilder、SqlSessionFactory、SqlSession可以说每个MyBatis都是以一个SqlSessionFactory实例为中心的。SqlSessionFactory实例可以通过SqlSessionFactoryBuilder来构建。一是可以通过XML配置文件的方式来构建SqlSessionFact">
<meta property="og:type" content="article">
<meta property="og:title" content="kyssion-blog">
<meta property="og:url" content="http://yoursite.com/2018/10/09/深入理解mybatis（五）java api/index.html">
<meta property="og:site_name" content="kyssion-blog">
<meta property="og:description" content="深入理解mybatis（五）java apiSqlSessionFactoryBuilder、SqlSessionFactory、SqlSession可以说每个MyBatis都是以一个SqlSessionFactory实例为中心的。SqlSessionFactory实例可以通过SqlSessionFactoryBuilder来构建。一是可以通过XML配置文件的方式来构建SqlSessionFact">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-10-09T07:22:37.341Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="kyssion-blog">
<meta name="twitter:description" content="深入理解mybatis（五）java apiSqlSessionFactoryBuilder、SqlSessionFactory、SqlSession可以说每个MyBatis都是以一个SqlSessionFactory实例为中心的。SqlSessionFactory实例可以通过SqlSessionFactoryBuilder来构建。一是可以通过XML配置文件的方式来构建SqlSessionFact">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/09/深入理解mybatis（五）java api/"/>





  <title> | kyssion-blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">kyssion-blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/09/深入理解mybatis（五）java api/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kyssion">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="kyssion-blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline"></h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-09T15:22:37+08:00">
                2018-10-09
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="深入理解mybatis（五）java-api"><a href="#深入理解mybatis（五）java-api" class="headerlink" title="深入理解mybatis（五）java api"></a>深入理解mybatis（五）java api</h2><h3 id="SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession"><a href="#SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession" class="headerlink" title="SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession"></a>SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession</h3><p>可以说每个MyBatis都是以一个SqlSessionFactory实例为中心的。SqlSessionFactory实例可以通过SqlSessionFactoryBuilder来构建。一是可以通过XML配置文件的方式来构建SqlSessionFactory，二是可以通过Java API的方式来构建。但不管通过什么方式都有一个Configuration贯穿始终，各种配置正是通过Configuration实例来完成实现。</p>
<h4 id="sqlSessionfactoryBuiler生成SqlSessionFactory的方法"><a href="#sqlSessionfactoryBuiler生成SqlSessionFactory的方法" class="headerlink" title="sqlSessionfactoryBuiler生成SqlSessionFactory的方法"></a>sqlSessionfactoryBuiler生成SqlSessionFactory的方法</h4><ol>
<li>使用java类配置实现(SqlSessionFactoryBuilder)</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 配置数据库链接池</span></span><br><span class="line">PooledDataSource pooledDataSource = <span class="keyword">new</span> PooledDataSource();</span><br><span class="line">pooledDataSource.setDriver(<span class="string">"com.mysql.jdbc.Driver"</span>);</span><br><span class="line">pooledDataSource.setUrl(<span class="string">"jdbc:mysql://127.0.0.1:3306/mybatis"</span>);</span><br><span class="line">pooledDataSource.setUsername(<span class="string">"kys"</span>);</span><br><span class="line">pooledDataSource.setPassword(<span class="string">"password"</span>);</span><br><span class="line"><span class="comment">//构建数据库事物方式</span></span><br><span class="line">TransactionFactory transactionFactory = <span class="keyword">new</span> JdbcTransactionFactory();</span><br><span class="line"><span class="comment">//创建数据库运行环境</span></span><br><span class="line">Environment environment = <span class="keyword">new</span> Environment(<span class="string">"development"</span>, transactionFactory, pooledDataSource);</span><br><span class="line"><span class="comment">//构建configuration对象</span></span><br><span class="line">Configuration configuration = <span class="keyword">new</span> Configuration(environment);</span><br><span class="line"><span class="comment">//注册别名</span></span><br><span class="line">configuration.getTypeAliasRegistry().registerAlias(<span class="string">"xxx"</span>, xxx.class);</span><br><span class="line"><span class="comment">//添加映射文件等</span></span><br><span class="line">configuration.addMapper(xxx.class);</span><br><span class="line"><span class="comment">//等等。。。。</span></span><br><span class="line">SqlSessionFactory sessionFactory = <span class="keyword">new</span> SqlSessionFactoryBuilder().build(configuration);</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>使用xml文档 输入流实现</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String resource = <span class="string">"org/mybatis/builder/mybatis-config.xml"</span>;</span><br><span class="line">InputStream inputStream = Resources.getResourceAsStream(resource);</span><br><span class="line">SqlSessionFactoryBuilder builder = <span class="keyword">new</span> SqlSessionFactoryBuilder();</span><br><span class="line">SqlSessionFactory factory = builder.build(inputStream);</span><br></pre></td></tr></table></figure>
<h4 id="SqlSessionFactory-创建SqlSession实例"><a href="#SqlSessionFactory-创建SqlSession实例" class="headerlink" title="SqlSessionFactory 创建SqlSession实例"></a>SqlSessionFactory 创建SqlSession实例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">()</span></span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(<span class="keyword">boolean</span> autoCommit)</span>  <span class="comment">//是否自动提交</span></span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(Connection connection)</span> </span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(TransactionIsolationLevel level)</span>  <span class="comment">//事物隔离级别</span></span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(ExecutorType execType,TransactionIsolationLevel level)</span></span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(ExecutorType execType)</span>  <span class="comment">// 预处理问题</span></span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(ExecutorType execType, <span class="keyword">boolean</span> autoCommit)</span></span></span><br><span class="line"><span class="function">SqlSession <span class="title">openSession</span><span class="params">(ExecutorType execType, Connection connection)</span></span></span><br><span class="line"><span class="function">Configuration <span class="title">getConfiguration</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>
<p><strong>相关参数配置：</strong></p>
<ol>
<li>事物隔离级别</li>
</ol>
<p>NONE(无),READ_UNCOMMITTED(读未提交),READ_COMMITTED(读已提交),REPEA TABLE_READ(可重复阅读),SERIALIZA BLE(序列化)</p>
<ol start="2">
<li>ExecutorType(执行方式)</li>
</ol>
<ul>
<li>ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情。它为每个语句的执行创建一个新的预处理语句。</li>
<li>ExecutorType.REUSE: 这个执行器类型会复用预处理语句。</li>
<li>ExecutorType.BATCH: 这个执行器会批量执行所有更新语句,如果 - - SELECT 在它们中间执行还会标定它们是 必须的,来保证一个简单并易于理解的行为。</li>
</ul>
<h4 id="SqlSession-最核心的会话操作类"><a href="#SqlSession-最核心的会话操作类" class="headerlink" title="SqlSession 最核心的会话操作类"></a>SqlSession 最核心的会话操作类</h4><ol>
<li>语句执行方法</li>
</ol>
<p>这些方法被用来执行定义在 SQL 映射的 XML 文件中的 SELECT,INSERT,UPDA E T 和 DELETE 语句。它们都会自行解释,每一句都使用语句的 ID 属性和参数对象,参数可以 是原生类型(自动装箱或包装类) ,JavaBean,POJO 或 Map。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;T&gt; <span class="function">T <span class="title">selectOne</span><span class="params">(String statement, Object parameter)</span></span></span><br><span class="line"><span class="function">&lt;E&gt; List&lt;E&gt; <span class="title">selectList</span><span class="params">(String statement, Object parameter)</span></span></span><br><span class="line"><span class="function">&lt;K,V&gt; Map&lt;K,V&gt; <span class="title">selectMap</span><span class="params">(String statement, Object parameter, String mapKey)</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">insert</span><span class="params">(String statement, Object parameter)</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">update</span><span class="params">(String statement, Object parameter)</span></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">delete</span><span class="params">(String statement, Object parameter)</span></span></span><br></pre></td></tr></table></figure>
<p><strong>注意</strong>：selectOne 和 selectList 的不同仅仅是 selectOne 必须返回一个对象。 如果多余一个, 或者 没有返回 (或返回了 null) 那么就会抛出异常。 , 如果你不知道需要多少对象, 使用 selectList。</p>
<p>最后,还有查询方法的三个高级版本,它们允许你限制返回行数的范围,或者提供自定 义结果控制逻辑,这通常用于大量的数据集合。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;E&gt; <span class="function">List&lt;E&gt; <span class="title">selectList</span> <span class="params">(String statement, Object parameter, RowBounds rowBounds)</span></span></span><br><span class="line"><span class="function">&lt;K,V&gt; Map&lt;K,V&gt; <span class="title">selectMap</span><span class="params">(String statement, Object parameter, String mapKey, RowBounds rowbounds)</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">select</span> <span class="params">(String statement, Object parameter, ResultHandler&lt;T&gt; handler)</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">select</span> <span class="params">(String statement, Object parameter, RowBounds rowBounds, ResultHandler&lt;T&gt; handler)</span></span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>RowBounds 参数会告诉 MyBatis 略过指定数量的记录,还有限制返回结果的数量。 </p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> offset = <span class="number">100</span>;  <span class="comment">//返回结果集的数量</span></span><br><span class="line"><span class="keyword">int</span> limit = <span class="number">25</span>;    <span class="comment">//忽略掉的行数</span></span><br><span class="line">RowBounds rowBounds = <span class="keyword">new</span> RowBounds(offset, limit);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>ResultHandler 参数允许你按你喜欢的方式处理每一行。</p>
</blockquote>
<p>它的接口很简单。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> org.apache.ibatis.session;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ResultHandler</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">handleResult</span><span class="params">(ResultContext&lt;? extends T&gt; context)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>ResultContext 参数允许你访问结果对象本身、被创建的对象数目、以及返回值为 Boolean 的 stop 方法，你可以使用此 stop 方法来停止 MyBatis 加载更多的结果。<br>使用 ResultHandler 的时候需要注意以下两种限制：</p>
<ul>
<li>从被 ResultHandler 调用的方法返回的数据不会被缓存。</li>
<li>当使用结果映射集（resultMap）时，MyBatis 大多数情况下需要数行结果来构造外键对象。如果你正在使用 ResultHandler，你可以给出外键（association）或者集合（collection）尚未赋值的对象。</li>
</ul>
<ol start="2">
<li>批量立即更新方法(Flush Method)</li>
</ol>
<p>有一个方法可以刷新（执行）存储在JDBC驱动类中的批量更新语句。当你将ExecutorType.BATCH作为ExecutorType使用时可以采用此方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">List&lt;BatchResult&gt; <span class="title">flushStatements</span><span class="params">()</span></span></span><br></pre></td></tr></table></figure>
<ol start="3">
<li>事务控制方法</li>
</ol>
<p><strong>注意</strong>：如果你已经选择了自动提交或你正在使用外部事务管理器,这就没有任何效果了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">commit</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">commit</span><span class="params">(<span class="keyword">boolean</span> force)</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">rollback</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">rollback</span><span class="params">(<span class="keyword">boolean</span> force)</span></span></span><br></pre></td></tr></table></figure>
<ol start="4">
<li>清理Session级的缓存</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">List&lt;BatchResult&gt; <span class="keyword">void</span> <span class="title">clearCache</span><span class="params">()</span></span></span><br></pre></td></tr></table></figure>
<p>SqlSession 实例有一个本地缓存在执行 update,commit,rollback 和 close 时被清理。要 明确地关闭它(获取打算做更多的工作) ,你可以调用 clearCache()。</p>
<ol start="5">
<li>确保 SqlSession 被关闭</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">List&lt;BatchResult&gt; <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">`</span></span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">SqlSession session = sqlSessionFactory.openSession();</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="comment">// following 3 lines pseudocod for "doing some work"</span></span><br><span class="line">    session.insert(...);</span><br><span class="line">    session.update(...);</span><br><span class="line">    session.delete(...);</span><br><span class="line">    session.commit();</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    session.close();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//java7以上使用try-with-resources语句</span></span><br><span class="line"><span class="keyword">try</span> (SqlSession session = sqlSessionFactory.openSession()) &#123;</span><br><span class="line">    <span class="comment">// following 3 lines pseudocode for "doing some work"</span></span><br><span class="line">    session.insert(...);</span><br><span class="line">    session.update(...);</span><br><span class="line">    session.delete(...);</span><br><span class="line">    session.commit();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>高级应用 使用映射器 和常用注释操作</li>
</ol>
<p>type是mybatis的映射器类，是一个java接口，可以将接口类比成mybatis的map文件，包名称相当于xml中的namespace，而 select delete insert update 中的id属性 对应的 接口中的方法</p>
<p>最常用注解，用来进行动态的注入属性</p>
<table>
<thead>
<tr>
<th>注解</th>
<th>使用对象</th>
<th>相对应的XML</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>@CacheNamespace</td>
<td>类</td>
<td>&lt;cache&gt;</td>
<td>为给定的命名空间（比如类）配置缓存。属性有：implemetation,eviction,flushInterval,size,readWrite,blocking和properties。</td>
</tr>
<tr>
<td>@Property</td>
<td>N/A</td>
<td>&lt;property&gt;</td>
<td>指定参数值或占位值（placeholder）（能被mybatis-config.xml内的配置属性覆盖）。属性有：name,value。（仅在MyBatis3.4.2以上版本生效）</td>
</tr>
<tr>
<td>@CacheNamespaceRef</td>
<td>类</td>
<td>&lt;cacheRef&gt;</td>
<td>参照另外一个命名空间的缓存来使用。属性有：value,name。如果你使用了这个注解，你应设置value或者name属性的其中一个。value属性用于指定Java类型而指定命名空间（命名空间名就是指定的Java类型的全限定名），name属性（这个属性仅在MyBatis3.4.2以上版本生效）直接指定了命名空间的名字。</td>
</tr>
<tr>
<td>@ConstructorArgs</td>
<td>方法</td>
<td>&lt;constructor&gt;</td>
<td>收集一组结果传递给一个结果对象的构造方法。属性有：value，它是形式参数数组。</td>
</tr>
<tr>
<td>@Arg</td>
<td>N/A</td>
<td>&lt;arg&gt;</td>
<td>单参数构造方法，是ConstructorArgs集合的一部分。属性有：id,column,javaType,jdbcType,typeHandler,select和resultMap。id属性是布尔值，来标识用于比较的属性，和&lt;idArg&gt;XML元素相似。</td>
</tr>
<tr>
<td>&lt;idArg&gt;</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>@TypeDiscriminator</td>
<td>方法</td>
<td>&lt;discriminator&gt;</td>
<td>一组实例值被用来决定结果映射的表现。属性有：column,javaType,jdbcType,typeHandler和cases。cases属性是实例数组。</td>
</tr>
<tr>
<td>@Case</td>
<td>N/A</td>
<td>&lt;case&gt;</td>
<td>单独实例的值和它对应的映射。属性有：value,type,results。results属性是结果数组，因此这个注解和实际的ResultMap很相似，由下面的Results注解指定。</td>
</tr>
<tr>
<td>@Results</td>
<td>方法</td>
<td>&lt;resultMap&gt;</td>
<td>结果映射的列表，包含了一个特别结果列如何被映射到属性或字段的详情。属性有：value,id。value属性是Result注解的数组。这个id的属性是结果映射的名称。</td>
</tr>
<tr>
<td>@Result</td>
<td>N/A</td>
<td>&lt;result&gt;</td>
<td>在列和属性或字段之间的单独结果映射。属性有：id,column,javaType,jdbcType,typeHandler,one,many。id属性是一个布尔值，来标识应该被用于比较（和在XML映射中的&lt;id&gt;相似）的属性。one属性是单独的联系，和&lt;association&gt;相似，而many属性是对集合而言的，和&lt;collection&gt;相似。它们这样命名是为了避免名称冲突。</td>
</tr>
<tr>
<td>&lt;id&gt;</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>@One</td>
<td>N/A</td>
<td>&lt;association&gt;</td>
<td>复杂类型的单独属性值映射。属性有：select，已映射语句（也就是映射器方法）的全限定名，它可以加载合适类型的实例。fetchType会覆盖全局的配置参数lazyLoadingEnabled。注意联合映射在注解API中是不支持的。这是因为Java注解的限制,不允许循环引用。</td>
</tr>
<tr>
<td>@Many</td>
<td>N/A</td>
<td>&lt;collection&gt;</td>
<td>映射到复杂类型的集合属性。属性有：select，已映射语句（也就是映射器方法）的全限定名，它可以加载合适类型的实例的集合，fetchType会覆盖全局的配置参数lazyLoadingEnabled。注意联合映射在注解API中是不支持的。这是因为Java注解的限制，不允许循环引用</td>
</tr>
<tr>
<td>@MapKey</td>
<td>方法</td>
<td></td>
<td>这是一个用在返回值为Map的方法上的注解。它能够将存放对象的List转化为key值为对象的某一属性的Map。属性有：value，填入的是对象的属性名，作为Map的key值。</td>
</tr>
<tr>
<td>@Options</td>
<td>方法</td>
<td>映射语句的属性</td>
<td>这个注解提供访问大范围的交换和配置选项的入口，它们通常在映射语句上作为属性出现。Options注解提供了通俗易懂的方式来访问它们，而不是让每条语句注解变复杂。属性有：useCache=true,flushCache=FlushCachePolicy.DEFAULT,resultSetType=FORWARD_ONLY,statementType=PREPARED,fetchSize=-1,timeout=-1,useGeneratedKeys=false,keyProperty=”id”,keyColumn=””,resultSets=””。值得一提的是，Java注解无法指定null值。因此，一旦你使用了Options注解，你的语句就会被上述属性的默认值所影响。要注意避免默认值带来的预期以外的行为。</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>注意：keyColumn属性只在某些数据库中有效（如Oracle、PostgreSQL等）。请在插入语句一节查看更多关于keyColumn和keyProperty两者的有效值详情。</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>@Insert</td>
<td>方法</td>
<td>&lt;insert&gt;</td>
<td>这四个注解分别代表将会被执行的SQL语句。它们用字符串数组（或单个字符串）作为参数。如果传递的是字符串数组，字符串之间先会被填充一个空格再连接成单个完整的字符串。这有效避免了以Java代码构建SQL语句时的“丢失空格”的问题。然而，你也可以提前手动连接好字符串。属性有：value，填入的值是用来组成单个SQL语句的字符串数组。</td>
</tr>
<tr>
<td>@Update</td>
<td>&lt;update&gt;</td>
<td></td>
<td></td>
</tr>
<tr>
<td>@Delete</td>
<td>&lt;delete&gt;</td>
<td></td>
<td></td>
</tr>
<tr>
<td>@Select</td>
<td>&lt;select&gt;</td>
<td></td>
<td></td>
</tr>
<tr>
<td>@InsertProvider</td>
<td>方法</td>
<td>&lt;insert&gt;</td>
<td>允许构建动态SQL。这些备选的SQL注解允许你指定类名和返回在运行时执行的SQL语句的方法。（自从MyBatis3.4.6开始，你可以用CharSequence代替String来返回类型返回值了。）当执行映射语句的时候，MyBatis会实例化类并执行方法，类和方法就是填入了注解的值。你可以把已经传递给映射方法了的对象作为参数，”Mapperinterfacetype”和”Mappermethod”会经过ProviderContext（仅在MyBatis3.4.5及以上支持）作为参数值。（MyBatis3.4及以上的版本，支持多参数传入）属性有：type,method。type属性需填入类。method需填入该类定义了的方法名。注意接下来的小节将会讨论类，能帮助你更轻松地构建动态SQL。</td>
</tr>
<tr>
<td>@UpdateProvider</td>
<td>&lt;update&gt;</td>
<td></td>
<td></td>
</tr>
<tr>
<td>@DeleteProvider</td>
<td>&lt;delete&gt;</td>
<td></td>
<td></td>
</tr>
<tr>
<td>@SelectProvider</td>
<td>&lt;select&gt;</td>
<td></td>
<td></td>
</tr>
<tr>
<td>@Param</td>
<td>参数</td>
<td>N/A</td>
<td>如果你的映射方法的形参有多个，这个注解使用在映射方法的参数上就能为它们取自定义名字。若不给出自定义名字，多参数（不包括RowBounds参数）则先以”param”作前缀，再加上它们的参数位置作为参数别名。例如#{param1},#{param2}，这个是默认值。如果注解是@Param(“person”)，那么参数就会被命名为#{person}。</td>
</tr>
<tr>
<td>@SelectKey</td>
<td>方法</td>
<td>&lt;selectKey&gt;</td>
<td>这个注解的功能与&lt;selectKey&gt;标签完全一致，用在已经被@Insert或@InsertProvider或@Update或@UpdateProvider注解了的方法上。若在未被上述四个注解的方法上作@SelectKey注解则视为无效。如果你指定了@SelectKey注解，那么MyBatis就会忽略掉由@Options注解所设置的生成主键或设置（configuration）属性。属性有：statement填入将会被执行的SQL字符串数组，keyProperty填入将会被更新的参数对象的属性的值，before填入true或false以指明SQL语句应被在插入语句的之前还是之后执行。resultType填入keyProperty的Java类型和用Statement、PreparedStatement和CallableStatement中的STATEMENT、PREPARED或CALLABLE中任一值填入statementType。默认值是PREPARED。</td>
</tr>
<tr>
<td>@ResultMap</td>
<td>方法</td>
<td>N/A</td>
<td>这个注解给@Select或者@SelectProvider提供在XML映射中的&lt;resultMap&gt;的id。这使得注解的select可以复用那些定义在XML中的ResultMap。如果同一select注解中还存在@Results或者@ConstructorArgs，那么这两个注解将被此注解覆盖。</td>
</tr>
<tr>
<td>@ResultType</td>
<td>方法</td>
<td>N/A</td>
<td>此注解在使用了结果处理器的情况下使用。在这种情况下，返回类型为void，所以Mybatis必须有一种方式决定对象的类型，用于构造每行数据。如果有XML的结果映射，请使用@ResultMap注解。如果结果类型在XML的&lt;select&gt;节点中指定了，就不需要其他的注解了。其他情况下则使用此注解。比如，如果@Select注解在一个将使用结果处理器的方法上，那么返回类型必须是void并且这个注解（或者@ResultMap）必选。这个注解仅在方法返回类型是void的情况下生效。</td>
</tr>
<tr>
<td>@Flush</td>
<td>方法</td>
<td>N/A</td>
<td>如果使用了这个注解，定义在Mapper接口中的方法能够调用SqlSession#flushStatements()方法。（Mybatis3.3及以上）</td>
</tr>
</tbody>
</table>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/09/深入理解mybatis（七）mybatis和spring结合/" rel="next" title="">
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/10/09/深入分析spring的装箱扩展/" rel="prev" title="">
                 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">kyssion</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">133</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#深入理解mybatis（五）java-api"><span class="nav-number">1.</span> <span class="nav-text">深入理解mybatis（五）java api</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession"><span class="nav-number">1.1.</span> <span class="nav-text">SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#sqlSessionfactoryBuiler生成SqlSessionFactory的方法"><span class="nav-number">1.1.1.</span> <span class="nav-text">sqlSessionfactoryBuiler生成SqlSessionFactory的方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SqlSessionFactory-创建SqlSession实例"><span class="nav-number">1.1.2.</span> <span class="nav-text">SqlSessionFactory 创建SqlSession实例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SqlSession-最核心的会话操作类"><span class="nav-number">1.1.3.</span> <span class="nav-text">SqlSession 最核心的会话操作类</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kyssion</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
